import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Link } from 'react-router'
import { Table, Spin, Form, Row, Col, Input, Button, Select, TreeSelect, DatePicker, Checkbox, message, Dropdown, Menu, Icon } from 'antd'
import _ from 'lodash'
import moment from 'moment';

import Ajax from 'lib/Ajax'
import { addConfig } from 'actions/config'
import { getNewTreeData, findRowData, getNameByCode, confirmDelete, getYear, getPayCycleDom } from 'lib/fun'

const FormItem = Form.Item;
const SelectTreeNode = TreeSelect.TreeNode;
const { RangePicker } = DatePicker;
const Option = Select.Option;
const OptGroup = Select.OptGroup;
const SHOW_PARENT = TreeSelect.SHOW_PARENT;

class Filter extends Component {
  constructor(props) {
    super(props);
    this.state = {
      treeData: [],
    }
  }

  componentDidMount(){
    // this.loadArea();
    if(this.props.common.user&&this.props.common.user.user&&this.state.treeData.length == 0){
      this.setState({
        treeData:[{
          areaId: this.props.common.user.user.areaId,
          areaName: this.props.common.user.user.areaName,
        }]
      });
    }
  }

  componentWillReceiveProps(nextProps){
    if(nextProps.common.user&&nextProps.common.user.user&&this.state.treeData.length == 0){
      this.setState({
        treeData:[{
          areaId: nextProps.common.user.user.areaId,
          areaName: nextProps.common.user.user.areaName,
        }]
      });
    }
  }

  loadArea = (treeNode)=>{
    console.log('load area');
    var self = this;
    var selected = findRowData(self.state.treeData, treeNode?treeNode.props.eventKey:0, 'areaId');
    return new Promise((resolve) => {
      if(selected&&selected.children){
        resolve();
      }else{
        Ajax({
          url: '/area/list',
          data: {
            areaParentId: treeNode?treeNode.props.eventKey:0,
            perPage: 100
          },
          success: function(data){
            var treeData = self.state.treeData;
            if(treeNode&&self.state.treeData.length > 0){
              treeData = getNewTreeData(treeData, treeNode.props.eventKey, data.list, 'areaId');
            }else{
              treeData = data.list;
            }
            self.setState({
              treeData
            });
            resolve();
          },
          error: function(error){
            message.error(error);
          }
        });
      }
    });
  }

  handleSearch = (e) => {
    var self = this;
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      const { areaIds } = values;
      var backObj = {
        areaIds: areaIds?[areaIds]:undefined
      }
      self.props.handleFilter(backObj);
    });
  }


  handleReset = () => {
    this.props.form.resetFields();
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
    };
    const formItemLayout2 = {
      labelCol: { span: 5 },
      wrapperCol: { span: 19 },
    };
    const loop = data => data.map((item) => {
      if (item.children&&item.children.length > 0) {
        return <SelectTreeNode title={item.areaName} key={item.areaId+""} value={item.areaId + ""}>{loop(item.children)}</SelectTreeNode>;
      }
      console.log('isLeaf',item.children&&item.children.length == 0 );
      return <SelectTreeNode title={item.areaName} key={item.areaId+""} value={item.areaId + ""} isLeaf={item.children&&item.children.length == 0}/>;
    });
    const treeNodes = loop(this.state.treeData);
    const years = getYear();

    return (<Form
          horizontal
          className="ant-advanced-search-form"
          onSubmit={this.handleSearch}
        >
          <Row gutter={20}>
            <Col span={8}>
              <FormItem {...formItemLayout} label="补贴登记区划">
                {getFieldDecorator("areaIds", {
                  initialValue: this.state.treeData.length>0?this.state.treeData[0].areaId+"":""
                })(
                    this.props.treeData?<Select
                      size="default"
                    >
                      {
                        (this.props.treeData||[]).map(function(obj){
                          return (<Option key={obj.areaId+""} value={ obj.areaId+"" }>{ obj.areaName }</Option>)
                        })
                      }
                    </Select>:<TreeSelect
                      size="default"
                      loadData={ this.loadArea }
                    >
                      { treeNodes }
                    </TreeSelect>
                )}
              </FormItem>
            </Col>
            <Col>
              <div className="btn-box">
                <Button type="primary" htmlType="submit">查询</Button>
              </div>
            </Col>
          </Row>
        </Form>);
  }
}

function mapStateToProps(state) {
  return {
    config: state.config,
    common: state.common
  }
}

module.exports = connect(mapStateToProps)(Form.create()(Filter))